﻿Imports System.IO
Imports System.Windows.Forms
Imports NPOI.HSSF.UserModel
Imports NPOI.SS.UserModel
Imports NPOI.XSSF.UserModel

Public Class Frm_ExportClient
    Private ReadOnly Log As New LogSub(Sub(m) Txt_Log.AppendLogOnThread(m))

    Private Sub Frm_ExportClient_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Sy.UI.Form.ShadowForm.RegisterShadowForm(Me,, True)
        Icon = OemIcon
    End Sub
    Private Ids As Integer()
    Public Overloads Sub ShowDialog(Ids As Integer())
        Me.Ids = Ids
        ShowDialog(Owner)
    End Sub
    Private Sub Btn_UpLoad_Click(sender As Object, e As EventArgs) Handles Btn_Export.Click
        If Sy.Threading.ThreadExecutor.Instance.Execute(Sub() Nop()) Then
            Dim FD As New SaveFileDialog With {
                .Filter = $"Excel 工作簿(*.xlsx)|*.xlsx|Excel 97-2003工作簿(*.xls)|*.xls|Excel 启用宏的工作簿(*.xlsm)|*.xlsm",
                .Title = "选择导出路径",
                .FileName = $"Erp_Client_{Sy.DataTimeFormat.Fromat_yyyyMMddHHmmss}",
                .InitialDirectory = Sy.Environment.Path.Desktop
            }
            If FD.ShowDialog(Me) = DialogResult.OK Then
                Btn_Export.Enabled = False
                Dim FileFullPath = FD.FileName
                Lab_Path.Text = $"文件保存路径:{FileFullPath}"
                PBG_All.Value = 0
                Lab_Num.Text = $"0/0"
                Sy.Threading.ThreadExecutor.Instance.Execute(Sub() Export(FileFullPath))
            End If
        End If
    End Sub
    Private Sub Export(FileFullPath As String)
        Dim fileExt = IO.Path.GetExtension(FileFullPath).ToLower()
        Dim filepath = IO.Path.GetDirectoryName(FileFullPath)
        Dim filename = IO.Path.GetFileNameWithoutExtension(FileFullPath)
        Dim DirName = FileNameReplace($"Client_{filename}") '{DateTime.Now.ToString("yyyyMMddHH")
        Dim DirPath = IO.Path.Combine(filepath, DirName)
        Dim workbookFactory As Func(Of IWorkbook)
        'XSSFWorkbook 适用XLSX格式，HSSFWorkbook 适用XLS格式
        If fileExt.Equals(".xlsx") Then
            workbookFactory = Function() New XSSFWorkbook()
        ElseIf fileExt.Equals(".xlsm") Then
            workbookFactory = Function() New XSSFWorkbook(XSSFWorkbookType.XLSM)
        ElseIf fileExt.Equals(".xls") Then
            workbookFactory = Function() New HSSFWorkbook()
        Else
            Log("文件类型不支持,导出已终止!")
            Btn_Export.Enabled = True
            Exit Sub
        End If
        Log("初始化用户信息...")
        Dim workbook As IWorkbook = workbookFactory()
        '获取表头
        Dim HeaderLst As New List(Of List(Of String)) From
            {New List(Of String) From {"客户名称", "手机号", "工作邮箱", "个人邮箱", "公司电话", "职称", "领英地址",  "成交状态", "获取客户时间", "最后跟进时间", "最后跟进记录", "意向", "关注度", "分组名称", "来源", "类型", "创建时间", "更新时间"}}
        Dim RowIndex As Integer = 0
        Dim SheetName = "Purchase"
        Dim Sheet = workbook.CreateSheet(SheetName)
        RowIndex += CommonInvoke.Instance.FullData(Sheet, RowIndex, HeaderLst, Log)
        Log($"构建导出[{SheetName}]表头完成")
        Dim CurCount = 0
        Dim AllIds As New List(Of Integer)
        Ids.ForEach(Sub(r) AllIds.Add(r))
        Do
            Dim TempIDs As List(Of Integer) = AllIds.Take(5).ToList()
            Log($"正在获取ID为{String.Join(",", TempIDs)}的用户数据...")
            Dim Api As New Client.Export.GetClient(TempIDs)
            If Api.[Get](Log) Then
                Dim OrderData As New List(Of List(Of String))
                Dim Responses = Api.Response
                For Each Response In Responses
                    Dim Item As New List(Of String)
                    Item.Add(Response.name)
                    Item.Add(Response.mobile)
                    Item.Add(Response.email)
                    Item.Add(Response.personalEmail)
                    Item.Add(Response.CompanyTel)
                    Item.Add(Response.JobTitle)
                    Item.Add(Response.LinkedinUrl)
                    Item.Add(IIf(Response.dealStatus = 0, "未成交", "成交"))
                    Item.Add(Response.belongAt)
                    Item.Add(Response.followAt)
                    Item.Add(Response.followMessage)
                    Item.Add(IIf(Response.isIntention = 0, "无意向", "有意向"))
                    Item.Add(Response.attention)
                    Item.Add(Response.group?.name)
                    Item.Add(Response.source?.name)
                    Item.Add(Response.type.GetDescription())
                    Item.Add(Response.createdAt)
                    Item.Add(Response.updatedAt)
                    OrderData.Add(Item)
                    Log($"获取[{Response.name}]用户数据完成!")
                Next
                RowIndex += CommonInvoke.Instance.FullData(Sheet, RowIndex, OrderData, Log)
            Else
                Log($"获取[{String.Join(",", TempIDs)}]用户数据失败!")
            End If
            CurCount += TempIDs.Count
            AllIds.RemoveRange(0, TempIDs.Count)
            InvokEx(Sub()
                        PBG_All.Value = CurCount / Ids.Length
                        Lab_Num.Text = $"{CurCount}/{Ids.Length}"
                    End Sub)
        Loop Until AllIds.Count = 0
        Log($"获取所有用户数据完成!")
        Try
            Using fs = File.OpenWrite(FileFullPath)
                workbook.Write(fs)
            End Using
        Catch ex As Exception
            InvokEx(Sub()
                        Sy.UI.Form.MsgBox.Show($"导出失败:{ex.Message}",
                                               {"确定", "取消"},
                                               "警告",
                                               Me)
                        Btn_Export.Enabled = True
                    End Sub)
            Exit Sub
        End Try
        If InvokEx(Function() Sy.UI.Form.MsgBox.Show("导出完成，是否打开文件所在文件夹?",
                                                  {"打开", "跳过"},
                                                  "已完成", Me)) = Sy.UI.Form.DialogResult.A Then
            Sy.Cmd.Explorer.Execute(FileFullPath)
        End If
        InvokEx(Sub() Btn_Export.Enabled = True)
    End Sub
    Private Sub TitleBar1_ClickClose(sender As Object, e As FormClosingEventArgs) Handles TitleBar1.ClickClose
        If Sy.Threading.ThreadExecutor.Instance.IsAlive Then
            Sy.UI.Form.MsgBox.Show(Sy.Threading.ThreadExecutor.Instance.CurAbortThreadMsg,
                                   {"强制终止", "继续"},
                                   "退出警告",
                                   Me,
                                   {Sub() Sy.Threading.ThreadExecutor.Instance.Abort(), Sub() e.Cancel = True})
        End If
    End Sub
End Class